package com.atkins.spring.data;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class DummyGoonData implements IGoonData {

	private Map<Integer, IGoonData.GoonDetails> goons;
	
	public GoonList getGoonList() {
		
		GoonList l = new GoonList();
		l.setList( new ArrayList<IGoonData.GoonRef>() );
		
		for(GoonDetails d : goons.values() ){
			l.getList().add(new GoonRef(d.getId(), d.getName()));
		}

		return l;
	}

	public GoonDetails getGoonDetails(int id) {

		GoonDetails d = null;
		if(goons.containsKey(id)){
			d = goons.get(id);
		}
		
		return d;
	}

	public boolean saveGoonDetails(GoonDetails details){
		
		if(details.getId()==0){
			// New
			List<Integer> keys = this.asSortedList(goons.keySet());
			int newKey = keys.get(keys.size()-1) + 1;
			details.setId(newKey);
			goons.put(newKey, details);
		} else {
			if(goons.containsKey(details.getId())){
				goons.put(details.getId(), details);
			} else {
				//Throw exception
				return false;
			}
		}
		
		return true;
	}

	// Used for resource injection
	public void setGoons(Map<Integer, IGoonData.GoonDetails> goons) {
		this.goons = goons;
	}

	public <T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
	  List<T> list = new ArrayList<T>(c);
	  java.util.Collections.sort(list);
	  return list;
	}
}
